package com.scut.online_black_market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scut.online_black_market.dto.*;
import com.scut.online_black_market.dto.ChangeImage;

import com.scut.online_black_market.dto.OrderResponse;

import com.scut.online_black_market.dto.PictureAndName;
import com.scut.online_black_market.dto.RegisterRequest;
import com.scut.online_black_market.entity.Personal;
import com.scut.online_black_market.entity.ProductOrder;
import com.scut.online_black_market.entity.ProductSellout;
import com.scut.online_black_market.exception.RegisterException;
import com.scut.online_black_market.exception.UniversalException;
import com.scut.online_black_market.exception.VerifyCodeException;
import com.scut.online_black_market.mapper.PersonalMapper;
import com.scut.online_black_market.mapper.ProductOrderMapper;
import com.scut.online_black_market.mapper.ProductSelloutMapper;
import com.scut.online_black_market.service.MailService;
import com.scut.online_black_market.service.PersonalService;
import com.scut.online_black_market.utility.JwtUtil;
import com.scut.online_black_market.utility.RedisUtil;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

/**
 * create by yellowBroke on 2020年11月2日 22点29分
 */
@Service
public class PersonalServiceImpl implements PersonalService {

    @Resource
    private MailService mailService;

    @Resource
    private PersonalMapper personalMapper;

    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    @Resource
    private HttpServletRequest httpServletRequest;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private ProductSelloutMapper productSelloutMapper;

    @Resource
    private ProductOrderMapper productOrderMapper;

    @Override
    public void register(RegisterRequest registerRequest) throws VerifyCodeException, RegisterException {

        mailService.validateCode(registerRequest.getMail(),registerRequest.getValidateCode());

        //String password = registerRequest.getPassword();
        String password = passwordEncoder.encode(registerRequest.getPassword());

        Personal personal = Personal.builder()
                .studentNumber(registerRequest.getStudentNumber())
                .nickname("default" + String.valueOf(100000 + new Random().nextInt(899999)))
                .pictureAddress("http://47.99.159.129:8081/image/35e74ffaa0554c2ba9fc3b2567dd296d.jpg")
                .campus("南校")
                .address("大学城")
                .balance(0.0f)
                .password(password)
                .email(registerRequest.getMail())
                .build();

        PictureAndName pictureAndName = PictureAndName.builder()
                .nickname(personal.getNickname())
                .pictureUrl(personal.getPictureAddress())
                .build();

        redisUtil.set(personal.getStudentNumber(),pictureAndName);

        if (personalMapper.insert(personal) != 1) {
            redisUtil.del(personal.getStudentNumber());
            throw new RegisterException("注册失败，请重试!");
        }
    }

    @Override
    public Personal getPersonalInfo() {
        String studentNumber = jwtUtil.extractStudentNumber(httpServletRequest);

        Personal personalInfo = personalMapper.selectById(studentNumber);

        return personalInfo;
    }

    @Override
    public void changePersonalImage(ChangeImage changeImage) throws UniversalException {
        String studentNumber = jwtUtil.extractStudentNumber(httpServletRequest);

        if (!studentNumber.equals(changeImage.getStudentNumber())) {
            throw new UniversalException("权限错误");
        }

        Personal personal = personalMapper.selectById(studentNumber);
        personal.setPictureAddress(changeImage.getUrl()==null? personal.getPictureAddress() : changeImage.getUrl());
        if (personalMapper.updateById(personal) != 1){
            throw new UniversalException("头像修改失败");
        }
        PictureAndName pictureAndName = (PictureAndName) redisUtil.get(studentNumber);
        pictureAndName.setPictureUrl(changeImage.getUrl());
        redisUtil.set(studentNumber, pictureAndName);
    }

    @Override
    public List<OrderResponse> queryOrder() {

        String studentId = jwtUtil.extractStudentNumber(httpServletRequest);

        List<OrderResponse> orderList = new LinkedList<>();
        QueryWrapper<ProductOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("buyer_id", studentId);
        wrapper.eq("type", 1);
        List<ProductOrder> productOrderList = productOrderMapper.selectList(wrapper);
        for (ProductOrder order : productOrderList) {
//            QueryWrapper<ProductSellout> productWrapper = new QueryWrapper<>();
//            productWrapper.eq("product_id" , order.getProductId());
            ProductSellout productSellout = productSelloutMapper.selectById(order.getProductId());

            OrderResponse orderResponse = OrderResponse.builder()
                    .productId(productSellout.getProductId())
                    .productName(productSellout.getProductName())
                    .productPrice(productSellout.getProductPrice())
                    .productPictureLocation(productSellout.getProductPictureLocation())
                    .sellManId(productSellout.getSellmanId())
                    .buyTime(order.getBuyTime())
                    .state(order.getState())
                    .build();

            orderList.add(orderResponse);
        }
        return orderList;
    }

    @Override
    public void changePersonalNicknameAndAddress(ChangeNicknameAndAddress changeNicknameAndAddress) throws UniversalException {

        String studentNumber = jwtUtil.extractStudentNumber(httpServletRequest);

        if (!studentNumber.equals(changeNicknameAndAddress.getStudentNumber())) {
            throw new UniversalException("权限错误");
        }

        Personal personal = personalMapper.selectById(studentNumber);
        String originName = personal.getNickname();
        personal.setNickname(changeNicknameAndAddress.getNickname()==null? personal.getNickname() : changeNicknameAndAddress.getNickname());
        personal.setAddress(changeNicknameAndAddress.getAddress() == null ? personal.getAddress() : changeNicknameAndAddress.getAddress());
        personal.setCampus(changeNicknameAndAddress.getCampus()==null?personal.getCampus():changeNicknameAndAddress.getCampus());

        PictureAndName pictureAndName = (PictureAndName) redisUtil.get(studentNumber);
        pictureAndName.setNickname(changeNicknameAndAddress.getNickname() == null ? pictureAndName.getNickname() : changeNicknameAndAddress.getNickname());
        redisUtil.set(studentNumber, pictureAndName);

        if (personalMapper.updateById(personal) != 1){
            pictureAndName.setNickname(originName);
            redisUtil.set(studentNumber, pictureAndName);
            throw new UniversalException("昵称修改失败");
        }
    }
}
